package com.wbao.dianniu.im;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;


import com.wbao.dianniu.data.HeadData;
import com.wbao.dianniu.indexView.CharacterParser;
import com.wbao.dianniu.indexView.PinyinComparator;
import com.wbao.dianniu.indexView.SideBar;
import com.wbao.dianniu.indexView.SortAdapter;
import com.wbao.dianniu.indexView.SortModel;
import com.wbao.dianniu.indexView.SideBar.OnTouchingLetterChangedListener;
import com.wbao.dianniu.listener.IFriendListListener;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.manager.FriendListManager;
import com.wbao.dianniu.manager.ShareSDKManager;
import com.wbao.dianniu.utils.Utils;
import com.wbao.dianniu.R;

/**
 * 好友 fragment
 * 
 * @author yejianjun
 *
 */
public class FriendsFragment extends Fragment implements IFriendListListener{
	private SideBar sideBar;
	private TextView dialog;
	private SortAdapter adapter;
	private ListView sortListView;
	private FriendListManager manager;
	
	/**
	 * 汉字转换成拼音的类
	 */
	private CharacterParser characterParser;
	private List<SortModel> SourceDateList;
	private LinearLayout mFollow;
	private LinearLayout addFriends;
	
	/**
	 * 根据拼音来排列ListView里面的数据类
	 */
	private PinyinComparator pinyinComparator;

	public static FriendsFragment instance(Context context) {
		FriendsFragment view = new FriendsFragment();
		return view;
	}

	@Override
	@Nullable
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_friends, null);
		initView(view);
		/*
		//IM自带获取联系人列表
		List<IYWDBContact> contactsList = LoginSampleHelper.getInstance().getContactsFromCache();
		for (int i = 0; i < contactsList.size(); i++) {
			System.out.println(contactsList.get(i).getShowName());
		}*/
		return view;
	}
	
	
	private void initView(final View view){
		sideBar = (SideBar) view.findViewById(R.id.sidrbar);
		dialog = (TextView) view.findViewById(R.id.choose_indext_dialog);
		mFollow = (LinearLayout) view.findViewById(R.id.follow_linearlayout);
		addFriends = (LinearLayout) view.findViewById(R.id.add_friend_injoin);
		//我的关注 
		mFollow.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(getContext(), FollowListActivity.class);
				startActivity(intent);
			}
		});
		//邀请好友加入 
		addFriends.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				ShareSDKManager.getInstance().showShare(view.getContext(), "我正在玩电纽，打造自己的电商圈，您也赶快加入吧！", 3, GlobalContext.cdndownUrl + "logo.png", GlobalContext.accountId);
			}
		});
		
		//设置右侧触摸监听
		sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {
			@Override
			public void onTouchingLetterChanged(String s) {
				//该字母首次出现的位置
				int position = adapter.getPositionForSection(s.charAt(0));
				if(position != -1){
					sortListView.setSelection(position);
				}
			}
		});
		sideBar.setTextView(dialog);
		sortListView = (ListView) view.findViewById(R.id.country_lvcountry);
		sortListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				//这里要利用adapter.getItem(position)来获取当前position所对应的对象
				Integer accountId = ((SortModel)adapter.getItem(position)).getFriendId();
				Utils.intoHeadInfoActivity(accountId, getActivity());
			}
		});
		sortListView.setAdapter(adapter);
	}
	
	@Override
	public void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		manager = new FriendListManager(getActivity());
		manager.addFriendListener(this);
		manager.friendList(GlobalContext.accountId, 0, 999);
		//实例化汉字转拼音类
		characterParser = CharacterParser.getInstance();
		pinyinComparator = new PinyinComparator();
		//SourceDateList = filledData(getResources().getStringArray(R.array.date));
		SourceDateList = new ArrayList<SortModel>();
		adapter = new SortAdapter(getContext(), SourceDateList);
		// 根据a-z进行排序源数据
		Collections.sort(SourceDateList, pinyinComparator);
	}
	
	/**
	 * 为ListView填充数据
	 * @param date
	 * @return
	 */
	private List<SortModel> filledData(HeadData[] date){
		List<SortModel> mSortList = new ArrayList<SortModel>();
		
		for(int i=0; i<date.length; i++){
			SortModel sortModel = new SortModel();
			sortModel.setName(date[i].realName);
			sortModel.setFriendId(date[i].friendId);
			//汉字转换成拼音
			String pinyin = characterParser.getSelling(date[i].realName);
			String sortString = pinyin.substring(0, 1).toUpperCase();
			
			// 正则表达式，判断首字母是否是英文字母
			if(sortString.matches("[A-Z]")){
				sortModel.setSortLetters(sortString.toUpperCase());
			}else{
				sortModel.setSortLetters("#");
			}
			sortModel.setLabel(date[i].label);
			sortModel.setUrl(date[i].headPic);
			mSortList.add(sortModel);
		}
		return mSortList;
		
	}
	
	/**
	 * 根据输入框中的值来过滤数据并更新ListView
	 * @param filterStr
	 */
	private void filterData(String filterStr){
		List<SortModel> filterDateList = new ArrayList<SortModel>();
		
		if(TextUtils.isEmpty(filterStr)){
			filterDateList = SourceDateList;
		}else{
			filterDateList.clear();
			for(SortModel sortModel : SourceDateList){
				String name = sortModel.getName();
				if(name.indexOf(filterStr.toString()) != -1 || characterParser.getSelling(name).startsWith(filterStr.toString())){
					filterDateList.add(sortModel);
				}
			}
		}
		
		// 根据a-z进行排序
		Collections.sort(filterDateList, pinyinComparator);
		adapter.updateListView(filterDateList);
	}

	@Override
	public void onFriendFailure(int errorCode, String errorMsg) {
	}

	@Override
	public void onFriendSuccess(List<HeadData> objdata) {
		if(null == objdata){
			return;
		}
		HeadData[] heads = new HeadData[objdata.size()];
		for (int i = 0; i < heads.length; i++) {
			heads[i] = new HeadData();
			heads[i].headPic = objdata.get(i).headPic;
			heads[i].label = objdata.get(i).label;
			heads[i].realName = objdata.get(i).realName;
			heads[i].friendId = objdata.get(i).friendId;
		}
		SourceDateList = filledData(heads);
		adapter.updateListView(SourceDateList);
	}
	

}
